import createError from 'http-errors';
import express from 'express';
import path from 'path';
import cookieParser from 'cookie-parser';
import logger from 'morgan';
import rfs from 'rotating-file-stream';
import { expressjwt } from 'express-jwt';
// import session from 'express-session';
import swaggerJsdoc from 'swagger-jsdoc';
import swaggerUi from 'swagger-ui-express';
import cors from 'cors';

import { apiRouter, pagesRouter } from './routes/index.js';

var app = express();

// view engine setup
// app.set('views', path.join('./server/views'));
// app.set('view engine', 'jade');

// create a rotating write stream
var accessLogStream = rfs.createStream('access.log', {
  interval: '1d', // rotate daily
  path: path.join('./log'),
  compress: "gzip" // compress rotated files
})
app.use(logger('dev', { stream: accessLogStream }));

app.use(cors())
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join('./public')));

// Warning: connect.session() MemoryStore is not designed for a production environment
// app.use(session({
//   secret: 'SECREY_KEY',
//   resave: false,
//   saveUninitialized: true
// }));

// routes - Order list don't move
app.use('/api', expressjwt({
  secret: process.env.JWT_SECRET || 'SECREY_KEY', 
  algorithms: ["HS256"],
  credentialsRequired: false
}), apiRouter);

app.use('/', expressjwt({
  secret: process.env.JWT_SECRET || 'SECREY_KEY', 
  algorithms: ["HS256"],
  credentialsRequired: false
}), pagesRouter);

// swagger options
const options = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "Express API with Swagger",
      version: "0.1.0",
    }
  },
  apis: ["./src/controller/**/*.js"],
};

const specs = swaggerJsdoc(options);

app.use(
  "/docs",
  swaggerUi.serve,
  swaggerUi.setup(specs)
);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404)); // href: https://www.npmjs.com/package/http-errors
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

// module.exports = app;
export default app;
